package cn.lcc.utils.core.utils;

import org.apache.commons.lang3.StringUtils;

public class EscapeUtils {

    public static void main(String[] args) {
        System.out.println(EscapeUtils.escape("你有新的任务,请去西湖打扫卫生你有新的任务,请去西湖打扫卫生你有新的任务,请去西湖打扫卫生你有新的任务,请去西湖打扫卫生"));
    }

    /**
     * Escape编码  %u597d%31%32%33
     *
     * @param text 被编码的文本
     * @return 编码后的字符
     */
    public static String escape(String text)
    {
        if (StringUtils.isEmpty(text))
        {
            return StringUtils.EMPTY;
        }

        final StringBuilder tmp = new StringBuilder(text.length() * 6);
        char c;
        for (int i = 0; i < text.length(); i++)
        {
            c = text.charAt(i);
            if (c < 256)
            {
                if (c < 16)
                {
                    tmp.append("0000");
                }
                tmp.append(StringUtils.leftPad(Integer.toString(c, 16),4,"0"));
            }
            else
            {
                if (c <= 0xfff)
                {
                    tmp.append("0000");
                }
                tmp.append(StringUtils.leftPad(Integer.toString(c, 16),4,"0"));
            }
        }
        return tmp.toString();
    }

    /**
     * Escape解码
     *
     * @param content 被转义的内容
     * @return 解码后的字符串
     */
    public static String decode(String content)
    {
        if (StringUtils.isEmpty(content))
        {
            return content;
        }

        StringBuilder tmp = new StringBuilder(content.length());
        int lastPos = 0, pos = 0;
        char ch;
        while (lastPos < content.length())
        {
            pos = content.indexOf("%", lastPos);
            if (pos == lastPos)
            {
                if (content.charAt(pos + 1) == 'u')
                {
                    ch = (char) Integer.parseInt(content.substring(pos + 2, pos + 6), 16);
                    tmp.append(ch);
                    lastPos = pos + 6;
                }
                else
                {
                    ch = (char) Integer.parseInt(content.substring(pos + 1, pos + 3), 16);
                    tmp.append(ch);
                    lastPos = pos + 3;
                }
            }
            else
            {
                if (pos == -1)
                {
                    tmp.append(content.substring(lastPos));
                    lastPos = content.length();
                }
                else
                {
                    tmp.append(content, lastPos, pos);
                    lastPos = pos;
                }
            }
        }
        return tmp.toString();
    }



}
